/*
 * DA3.c
 *  Author: Henry Chan
 */
#define F_CPU 8000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
void delay(void);

int main(void)
{
	DDRB = 0xFF;		//Set PORTB to output Timer0
	DDRC = 0xFF;		//Set PORTC to output to LED9,LED10
	DDRD = 0x10;		//Set Port.D4(T0) to input clk
	PORTB = 0x00;		//Initialize PORTB to 0
	PORTC = 0x00;		//Initialize PORTC to 0
	TCNT0 = 0x00;		//Initialize Timer0 cnt
	TCCR0A = 0x00;		//Set Timer0 mode to Normal mode
	TCCR0B = 0x06;		//External Clock on falling edge

	TIMSK1 = (1 << TOIE1);	//Enable Timer1 Overflow interrupt
	sei();
	
    while(1)
    {
		PORTB = TCNT0;			//Output 8-bit Counter to PORTB
		delay();				//elapse 0.25s
		if(TCNT0 % 16 == 0)
			PORTC ^= (1 << 1);	//Toggle PORTC.1 (9th LED)
    }
}
ISR(TIMER1_OVF_vect){	//Timer1 has completed a 0.25s cycle
	TCCR1A = 0x00;		//Stop Timer1
	TCCR1B = 0x00;
	PORTC ^= (1 << 0);	//Toggle PORTC.0
	TIFR1 = 1<<TOV1;	//Reset flag register
}
void delay(){
	TCNT1H = 0xFF;			//Set Timer1 count value to 34286
	TCNT1L = 0xEF;			//for delay of 0.25s
	TCCR1A = 0x00;			//Set Timer1 mode to Normal mode
	TCCR1B = (1 << CS11) | (1 << CS10);	//64 Prescalar
	while((TIFR1 & 0x01) == 0){} //Run for 0.25s
}